const trackPlay = {
  pathArr: [], //轨迹经纬度
  TraceData: [], //轨迹原始数据
  T: 0, //播放还是暂停 0 是暂停 1是播放
  aL: 0, //运行到第几个点
  isSlide: false, //是否在滑动状态
  playState: false, //是否在播放状态
  playSpeed: 50, //播放速度
  X: 0, //拖拉事件第几个点
  init: function () {
    MarkerMovingControl = function (map, marker, path) {
      this._map = map;
      this._marker = marker;
      this._path = path;
      this._currentIndex = 0;
      marker.setPosition(path[0]);
      marker.setMap(map); //为Marker指定目标显示地图。当参数值取null时，地图上移除当前Marker：setMap(null)

    };
    MarkerMovingControl.prototype.move = function () {
      if (!this._listenToStepend) {
        this._listenToStepend = AMap.event.addListener(this, "stepend", function () {
          this.step();
        }, this);
      }
      this.step();
    };
    MarkerMovingControl.prototype.stop = function () {
      this._marker.stopMove();
    };
    MarkerMovingControl.prototype.restart = function () {
      this._marker.setPosition(this._path[0]);
      var icon;
      if (TraceData[0].CarState.trim() == "熄火") {
        icon = "../../AMap/vehicleR.png"
      } else if (TraceData[0].CarState.trim() == "行驶") {
        icon = "../../AMap/vehicleG.png"
      } else if (TraceData[0].CarState.trim() == "停车") {
        icon = "../../AMap/vehicleY.png"
      } else if (TraceData[0].CarState.trim() == "离线") {
        icon = "../../AMap/vehicleO.png"
      }

      this._marker.setIcon(icon); //改变车辆图片
      this._currentIndex = 0;
      this.stop();
    };
    MarkerMovingControl.prototype.previous = function () { //上一个点
      if (aL < 2) {
        this._marker.setPosition(this._path[aL - 1]);
        this._currentIndex = aL - 1;
        this.move();
      } else {
        this._marker.setPosition(this._path[aL - 2]);
        this._currentIndex = aL - 2;
        if (T === 1) { //播放状态
          this.move();
        } else {
          if (T === 0) { //暂停状态
            this.move();
            this.stop();
          }
        }
      }
    };
    MarkerMovingControl.prototype.next = function () { //直接跳到下一个点
      var pathlen = this._path.length;
      if (aL < pathlen) {
        this._marker.setPosition(this._path[aL]);
        this._currentIndex = aL;
        if (T === 1) {
          this.move();
        } else {
          if (T === 0) {
            this.move();
            this.stop();
          }
        }
      } else {
        alert("这已经是最后一个点！");
      }
    };
    MarkerMovingControl.prototype.skip = function () {
      this._marker.setPosition(this._path[trackPlayback.X]);
      this._currentIndex = trackPlayback.X;
      if (T === 1) {
        this.move();
      } else {
        if (T === 0) {
          this.move();
          this.stop();
        }
      }
      aL = trackPlayback.X;
    };
    MarkerMovingControl.prototype.step = function () {

      var bc = this._currentIndex + 1; //即将到达的下一个点
      if (bc <= this._path.length) {
        if (!this._listenToMoveend) {
          this._listenToMoveend = AMap.event.addListener(this._marker, "moveend", function () {
            this._currentIndex++; //结束一次 到下一个点

            AMap.event.trigger(this, "stepend");
            //事件流程 move (添加监听stepend) step(添加监听moveend) 到事件moving 结束后出发到moveend 然后触发到stepend 再次进入step

          }, this);
        }
        aL = bc; //赋值aL 在第几个点

        trackPlayback.showInfo();
        trackPlayback.alterImg();
        trackPlayback.X++;
        $("#play_slider").slider("setValue", trackPlayback.X); //滑块运动

        if (typeof (this._path[bc]) !== "undefined") {
          if (TraceData[aL].CarState != TraceData[aL - 1].CarState) {
            var icon;
            if (TraceData[aL].CarState.trim() == "熄火") {
              icon = "../../AMap/vehicleR.png"
            } else if (TraceData[aL].CarState.trim() == "行驶") {
              icon = "../../AMap/vehicleG.png"
            } else if (TraceData[aL].CarState.trim() == "停车") {
              icon = "../../AMap/vehicleY.png"
            } else if (TraceData[aL].CarState.trim() == "离线") {
              icon = "../../AMap/vehicleO.png"
            }

            this._marker.setIcon(icon); //改变车辆图片
          }

          var Xgap = Math.abs(parseFloat(TraceData[aL].LongitudeNew) - parseFloat(TraceData[aL - 1].LongitudeNew));
          var Ygap = Math.abs(parseFloat(TraceData[aL].LatitudeNew) - parseFloat(TraceData[aL - 1].LatitudeNew));
          if (Xgap < 0.000095 && Ygap < 0.000095) { //距离太小moveTo 方法不会进入moveend 事件  超过此范围才moveTo
            this._currentIndex++;
            if (T === 1 && !isSlide) { //播放状态且没有在滑动
              setTimeout(function () { //播放状态才回调
                this.step();

              }.bind(this), 120000 / trackPlayback.playSpeed);
            }
          } else {
            this._marker.moveTo(this._path[bc], trackPlayback.playSpeed);


            AMap.event.addListener(Mcar, "moving", function () { //J 代表车辆
              var pois = Mcar.getPosition();
              if (MapViewPort.contains(pois) !== true) {
                map.panTo(pois);
                trackPlayback.getViewPort();
              }
            });
          }

        }
      }

    };
  },
  trackMap: function () {
    if (pathArr.length > 1) { //ak 就是所有轨迹点
      Mcar = new AMap.Marker({
        map: map,
        position: pathArr[0],
        icon: "../../AMap/vehicle.png",
        offset: new AMap.Pixel(-26, -13),
        zIndex: 99999,
        autoRotation: true,
        angle: TraceData[0].Direction - 90
      });
      var icon;
      if (TraceData[0].CarState.trim() == "熄火") {
        icon = "../../AMap/vehicleR.png"
      } else if (TraceData[0].CarState.trim() == "行驶") {
        icon = "../../AMap/vehicleG.png"
      } else if (TraceData[0].CarState.trim() == "停车") {
        icon = "../../AMap/vehicleY.png"
      } else if (TraceData[0].CarState.trim() == "离线") {
        icon = "../../AMap/vehicleO.png"
      }

      Mcar.setIcon(icon); //改变车辆图片

      var be = new AMap.Polyline({
        map: map,
        path: pathArr,
        strokeColor: "#3366ff",
        strokeOpacity: 0.9,
        strokeWeight: 2
        // strokeStyle: "solid",
        //  showDir: true
      });
      k = new MarkerMovingControl(map, Mcar, pathArr);
      new AMap.Marker({ //开始点
        map: map,
        position: pathArr[0],
        offset: new AMap.Pixel(-20, -32),
        icon: new AMap.Icon({
          size: new AMap.Size(40, 40),
          image: "../../AMap/start.png",
          imageOffset: new AMap.Pixel(0, 0)
        })
      });
      new AMap.Marker({ //结束点
        map: map,
        position: pathArr[pathArr.length - 1],
        offset: new AMap.Pixel(-20, -32),
        icon: new AMap.Icon({
          size: new AMap.Size(40, 40),
          image: "../../AMap/end.png",
          imageOffset: new AMap.Pixel(0, 0)
        })
      });
      var self = this;
      AMap.event.addListener(Mcar, "click", function () { //为车加上点击事件
        var content = [];
        var obj = TraceData[aL - 1];
        content.push("车牌号码：" + selLicNum);
        content.push("在线状态：" + obj.CarState);
        content.push("速度(km/h)：" + obj.Speed);
        content.push("当前教练：" + obj.CoachName);
        content.push("当前学员：" + obj.StuName);
        content.push("定位时间：" + obj.GpsTime);
        content.push("位置：" + obj.Location);
        aC = new AMap.InfoWindow({
          content: content.join("<br/>"),
          offset: new AMap.Pixel(-1, -1),
          closeWhenClickMap: true
        });
        aC.open(map, Mcar.getPosition());
      });

    }
    map.setFitView();
    trackPlayback.getViewPort();
  },
  reset: function () { //复位
    pathArr = []; //轨迹经纬度
    Mcar = null;
    TraceData = [];
    trackPlayback.X = 0;
  },
  query: function (deviceNo, stime, etime, dataType, licNum) {
    var self = this;
    selLicNum = licNum;
    aH.ajax({
      type: "POST",
      url: "/Map/GetHisLocation",
      data: {
        "deviceNo": deviceNo,
        "stime": stime,
        "etime": etime,
        "dataType": dataType
      },
      dataType: "json",
      async: true,
      beforeSend: function () {
      },
      success: function (hisData) {
        if (hisData.length > 0) {
          self.playState = true;

          trackPlayback.reset();
          var markers = map.getAllOverlays('marker');
          var polylines = map.getAllOverlays('polyline');

          map.remove(markers);
          map.remove(polylines); //不清除训练场
          trackPlayback.getHistory(hisData);
        } else {
          $.messager.alert("提示", "这段时间无数据！");
        }

      },
      error: function () {
        self.playState = false;
      },

    });


  },
  getHistory: function (HisData) {
    console.log(HisData)
    TraceData = HisData;
    if (TraceData) {
      var traceLen = TraceData.length;
      for (var bi = 0; bi < traceLen; bi++) {
        var bM = TraceData[bi];
        var lng = bM.LongitudeNew;
        var lat = bM.LatitudeNew;
        if (lng !== 0 && lat !== 0) {
          pathArr.push([lng, lat]); //经纬度
        }
      }
    }
    setTimeout(function () {
      var dataArr = [];
      for (var i = 0; i < TraceData.length; i++) {
        var d = TraceData[i];
        dataArr.push({
          time: "(" + (i + 1) + ") " + d.GpsTime,
          status: d.CarState,
          speed: d.Speed + "km/h"
        });
      }
      $("#his_grd").datagrid({
        data: dataArr
      });
      $('#his_grd').datagrid({
        onDblClickCell: function (index, field, value) {
          I = aH(this).children("td:nth-child(11)").text();
          Q = aH(this).children("td:nth-child(12)").text();
          // var b0 = parseInt(aH(this).children("td:nth-child(1)").text());
          trackPlayback.X = index;
          k.skip();
        }
      });

      $("#play_slider").slider({
        max: TraceData.length,
        onComplete: function (val) { //slider拖拉事件
          trackPlayback.X = val;
          k.skip();
        },
        onChange: function (nval, oval) {}
      });

      trackPlayback.trackMap();

    }, 1)
  },
  skipAnimation: function () {
    k.skip();
  },
  stopAnimation: function () {
    trackPlayback.clears();
    k.stop();
    playState = false;
  },
  pauseAnimation: function () { //暂停动画
    T = 0; //暂停状态
    k.stop();
    var content = [];
    var obj = TraceData[aL - 1];
    content.push("车牌号码：" + selLicNum);
    content.push("在线状态：" + obj.CarState);
    content.push("速度(km/h)：" + obj.Speed);
    content.push("当前教练：" + obj.CoachName);
    content.push("当前学员：" + obj.StuName);
    content.push("定位时间：" + obj.GpsTime);
    content.push("位置：" + obj.Location);
    aC = new AMap.InfoWindow({
      content: content.join("<br/>"),
      offset: new AMap.Pixel(-20, -13),
      closeWhenClickMap: true
    });
    aC.open(map, Mcar.getPosition());
  },
  startAnimation: function () {
    if (this.playState) {
      T = 1; //播放状态
      k.move();
      map.clearInfoWindow();
      map.setZoomAndCenter(18, [TraceData[aL - 1].LongitudeNew, TraceData[aL - 1].LatitudeNew]);
    } else {
      $.messager.alert("提示", "请先查询数据！");
    }

  },
  restartAnimation: function () {
    T = 0;
    k.stop();
    playState = false;
    if (k !== undefined) {
      k.restart();
    }
    this.X = 0;
    $("#play_slider").slider('reset');

  },
  datetime_to_unix: function (datetime) {
    var tmp_datetime = datetime.replace(/:/g, '-');
    tmp_datetime = tmp_datetime.replace(/\//g, '-');
    tmp_datetime = tmp_datetime.replace(/ /g, '-');
    var arr = tmp_datetime.split("-");
    var now = new Date(Date.UTC(arr[0], arr[1] - 1, arr[2], arr[3] - 8, arr[4], arr[5]));
    return parseInt(now.getTime());
  },
  changeDirection: function (angle) { //转换出方向
    if (angle <= 22)
      return "北";
    else if (angle > 22 && angle <= (45 + 22))
      return "东北";
    else if (angle > (45 + 22) && angle <= (90 + 22))
      return "东";
    else if (angle > (90 + 22) && angle <= (90 + 45 + 22))
      return "东南";
    else if (angle > (90 + 45 + 22) && angle <= (180 + 22))
      return "南";
    else if (angle > (180 + 22) && angle <= (180 + 45 + 22))
      return "西南";
    else if (angle > (180 + 45 + 22) && angle <= (270 + 22))
      return "西";
    else if (angle > (270 + 22) && angle <= (270 + 45 + 22))
      return "西北";
    else if (angle > (270 + 45 + 22))
      return "北";
    else if (angle == null)
      return "";
    else
      return "";
  },
}
